package org.wmq.shopmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wmq.shopmanager.mapper.SystemRoleMenuMapper;
import org.wmq.shopmanager.service.SystemMenuService;
import org.wmq.shopmanager.service.SystemRoleMenuService;
import org.wmq.shopmodel.DTO.system.SystemRoleMenuAssignDTO;
import org.wmq.shopmodel.Entity.system.SystemMenu;
import org.wmq.shopmodel.Entity.system.SystemRoleMenu;
import org.wmq.shopmodel.VO.system.SystemRoleMenuListVO;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SystemRoleMenuServiceImpl extends ServiceImpl<SystemRoleMenuMapper, SystemRoleMenu> implements SystemRoleMenuService {
    private final SystemRoleMenuMapper systemRoleMenuMapper;
    private final SystemMenuService systemMenuService;

    @Override
    public SystemRoleMenuListVO getAllMenuAndAssignedRoleMenu(Long systemRoleId) {
        List<SystemMenu> treeStructureSystemMenuList = this.systemMenuService.getNodes();
        List<SystemRoleMenu> systemRoleMenus = this.selectByRoleId(systemRoleId);
        List<Long> assignedSystemMenuIdList = new ArrayList<>();
        for (SystemRoleMenu systemRoleMenu:systemRoleMenus){
            assignedSystemMenuIdList.add(systemRoleMenu.getSystemMenuId());
        }
        SystemRoleMenuListVO result = new SystemRoleMenuListVO();
        result.setTreeStructureSystemMenuList(treeStructureSystemMenuList);
        result.setAssignedSystemMenuIdList(assignedSystemMenuIdList);
        return result;
    }

    @Override
    @Transactional
    public void assignMenuToRole(SystemRoleMenuAssignDTO systemRoleMenuAssignDTO) {
        Long systemRoleId = systemRoleMenuAssignDTO.getSystemRoleId();
        this.deleteBySystemRoleId(systemRoleId);
        List<SystemRoleMenu> list = new ArrayList<>();
        for (Long systemMenuId:systemRoleMenuAssignDTO.getSystemMenuIdList()){
            SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
            systemRoleMenu.setSystemRoleId(systemRoleId);
            systemRoleMenu.setSystemMenuId(systemMenuId);
            list.add(systemRoleMenu);
        }
        this.saveBatch(list);
    }

    private List<SystemRoleMenu> selectByRoleId(Long systemRoleId) {
        LambdaQueryWrapper<SystemRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemRoleMenu::getSystemRoleId,systemRoleId);
        return this.list(queryWrapper);
    }

    private void deleteBySystemRoleId(Long systemRoleId) {
        LambdaQueryWrapper<SystemRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemRoleMenu::getSystemRoleId,systemRoleId);
        this.remove(queryWrapper);
    }
}
